<template>
  <div class="va-df-ire">
    <div class="va-df-ire-toolbar" ref="ele_toolbar"></div>
    <div class="va-df-ire-editarea" ref="ele_editor"></div>
  </div>
</template>

<script>
  import _ from 'lodash'
  import Editor from 'wangeditor'

  export default {
    props: {
      value: {},
      field: {
        type: Object,
        default () {
          return {}
        }
      },
      disabled: Boolean
    },
    data () {
      return {
        currentHtml: '',
        editor: null,
        updateContentDebounce: _.debounce(this.commitContent, 100, {leading: true})
      }
    },
    mounted () {
      this.editor = new Editor(this.$refs.ele_toolbar, this.$refs.ele_editor)
      if (this.field.richEditorConfig) {
        _.forOwn(this.field.richEditorConfig, (val, key) => {
          this.editor.customConfig[key] = val
        })
      }
      this.editor.customConfig.onchange = html => {
        this.currentHtml = html
        this.updateContentDebounce(html)
      }
      this.editor.create()
      if (this.value) {
        this.editor.txt.html(this.value)
      }
      if (this.disabled) {
        this.editor.$textElem.attr('contenteditable', false)
      }
    },
    methods: {
      commitContent (html) {
        if (html !== this.value) {
          this.$emit('input', html)
        }
      }
    },
    watch: {
      value () {
        if (this.value === this.currentHtml) {
          return
        }
        if (this.editor) {
          this.editor.txt.html(this.value)
        }
      },
      disabled () {
        this.editor.$textElem.attr('contenteditable', !!this.disabled)
      }
    }
  }
</script>
